package org.jcnc.labreport.util;

import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Node;

public class MarkdownConverter {

    private static class Holder {
        static final Parser PARSER = Parser.builder().build();
        static final HtmlRenderer RENDERER = HtmlRenderer.builder().build();
    }

    public static String convertToHtml(String markdown) {
        Node document = Holder.PARSER.parse(removeCodeFence(markdown));
        String htmlContent = Holder.RENDERER.render(document);

        return "<!DOCTYPE html>\n"
                + "<html lang=\"zh-CN\">\n"
                + "<head>\n"
                + "    <meta charset=\"UTF-8\">\n"
                + "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"
                + "    <title>实验报告</title>\n"
                + "</head>\n"
                + "<body>\n"
                + htmlContent + "\n"
                + "</body>\n"
                + "</html>";
    }

    public static String removeCodeFence(String markdown) {
        if (markdown.startsWith("```")) {
            String[] lines = markdown.split("\n", -1);
            if (lines.length >= 2 && lines[lines.length - 1].startsWith("```")) {
                StringBuilder sb = new StringBuilder();
                for (int i = 1; i < lines.length - 1; i++) {
                    sb.append(lines[i]).append("\n");
                }
                return sb.toString();
            }
        }
        return markdown;
    }
}
